# app/api/routes/machines.py
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional

from app.core.database import get_db
from app.schemas import schemas
from app.crud import crud
from app.api.routes.auth import get_current_user

router = APIRouter()


@router.get("/", response_model=List[schemas.Machine])
def read_machines(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    return crud.get_machines(db, skip=skip, limit=limit)


@router.get("/{machine_id}", response_model=schemas.Machine)
def get_machine_by_id(
    machine_id: int,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    machine = crud.get_machine(db, machine_id=machine_id)
    if machine is None:
        raise HTTPException(status_code=404, detail="机器不存在")
    return machine


@router.get("/available/{room_id}")
def get_available_machines(
    room_id: int,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    result = crud.get_available_machines(db, room_id=room_id)
    if result is None:
        raise HTTPException("异常")
    return result


@router.post("/", response_model=schemas.Machine)
def create_machine(
    machine: schemas.MachineCreate,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    return crud.create_machine(db=db, machine=machine)


@router.patch("/{machine_id}/status")
def update_machine_status(
    machine_id: int,
    status: str,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    if crud.update_machine_status(db=db, machine_id=machine_id, status=status) is None:
        raise HTTPException(
            status_code=400, detail=f"machine: {machine_id} 更新为 {status} 失败"
        )
    return {
        "machine_id": machine_id,
        "message": "机器状态更新成功",
        "new_status": status,
    }

@router.delete("/{machine_id}")
def delete_machine(
    machine_id: int,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    result = crud.delete_machine(db, machine_id)
    if result is None:
        raise HTTPException(status_code=400, detail="删除失败")
    return {"status": "successful", "message": "删除成功"}